package service

import (
	"fmt"
	"sysu-giep/internal/database/models"
	"time"

	"gorm.io/gorm"
)

type AdminService struct {
	db *gorm.DB
}

func NewAdminService(db *gorm.DB) *AdminService {
	return &AdminService{
		db: db,
	}
}

// GetUsers 获取所有用户列表
func (s *AdminService) GetUsers(page, size int, role, status string) ([]models.User, int64, error) {
	var users []models.User
	var total int64

	query := s.db.Model(&models.User{})

	// 角色筛选
	if role != "" {
		query = query.Where("role = ?", role)
	}

	// 状态筛选
	if status != "" {
		query = query.Where("status = ?", status)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * size
	if err := query.Offset(offset).Limit(size).Find(&users).Error; err != nil {
		return nil, 0, err
	}

	return users, total, nil
}

// UpdateUserStatus 更新用户状态
func (s *AdminService) UpdateUserStatus(userID uint, status models.UserStatus) error {
	return s.db.Model(&models.User{}).Where("id = ?", userID).Update("status", status).Error
}

// GetProjects 获取所有课题列表
func (s *AdminService) GetProjects(page, size int, status string) ([]models.Project, int64, error) {
	var projects []models.Project
	var total int64

	query := s.db.Model(&models.Project{})

	// 状态筛选
	if status != "" {
		query = query.Where("status = ?", status)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * size
	if err := query.Preload("Creator").
		Offset(offset).
		Limit(size).
		Find(&projects).Error; err != nil {
		return nil, 0, err
	}

	return projects, total, nil
}

// UpdateProjectStatus 更新课题状态
func (s *AdminService) UpdateProjectStatus(projectID uint, status models.ProjectStatus) error {
	return s.db.Model(&models.Project{}).Where("id = ?", projectID).Update("status", status).Error
}

// GetApplications 获取所有申请列表
func (s *AdminService) GetApplications(page, size int, status string) ([]models.Application, int64, error) {
	var applications []models.Application
	var total int64

	query := s.db.Model(&models.Application{})

	// 状态筛选
	if status != "" {
		query = query.Where("status = ?", status)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * size
	if err := query.Preload("Project").
		Preload("Applicant").
		Preload("Reviewer").
		Offset(offset).
		Limit(size).
		Find(&applications).Error; err != nil {
		return nil, 0, err
	}

	return applications, total, nil
}

// UpdateApplicationStatus 更新申请状态
func (s *AdminService) UpdateApplicationStatus(applicationID uint, status models.ApplicationStatus, feedback string) error {
	updates := map[string]interface{}{
		"status": status,
	}

	if feedback != "" {
		updates["feedback"] = feedback
	}

	return s.db.Model(&models.Application{}).Where("id = ?", applicationID).Updates(updates).Error
}

// GetStatistics 获取平台统计信息
func (s *AdminService) GetStatistics() (map[string]interface{}, error) {
	statistics := make(map[string]interface{})

	// 用户统计
	var totalUsers int64
	if err := s.db.Model(&models.User{}).Count(&totalUsers).Error; err != nil {
		return nil, err
	}
	statistics["total_users"] = totalUsers

	// 角色分布
	var roleDistribution []struct {
		Role  string `json:"role"`
		Count int64  `json:"count"`
	}
	if err := s.db.Model(&models.User{}).
		Select("role, count(*) as count").
		Group("role").
		Scan(&roleDistribution).Error; err != nil {
		return nil, err
	}
	statistics["user_distribution"] = roleDistribution

	// 课题统计
	var totalProjects int64
	if err := s.db.Model(&models.Project{}).Count(&totalProjects).Error; err != nil {
		return nil, err
	}
	statistics["total_projects"] = totalProjects

	// 课题状态分布
	var projectStatusDistribution []struct {
		Status string `json:"status"`
		Count  int64  `json:"count"`
	}
	if err := s.db.Model(&models.Project{}).
		Select("status, count(*) as count").
		Group("status").
		Scan(&projectStatusDistribution).Error; err != nil {
		return nil, err
	}
	statistics["project_distribution"] = projectStatusDistribution

	// 申请统计
	var totalApplications int64
	if err := s.db.Model(&models.Application{}).Count(&totalApplications).Error; err != nil {
		return nil, err
	}
	statistics["total_applications"] = totalApplications

	// 申请状态分布
	var applicationStatusDistribution []struct {
		Status string `json:"status"`
		Count  int64  `json:"count"`
	}
	if err := s.db.Model(&models.Application{}).
		Select("status, count(*) as count").
		Group("status").
		Scan(&applicationStatusDistribution).Error; err != nil {
		return nil, err
	}
	statistics["application_distribution"] = applicationStatusDistribution

	// 匹配统计
	var totalMatches int64
	if err := s.db.Model(&models.ProjectMatch{}).Count(&totalMatches).Error; err != nil {
		return nil, err
	}
	statistics["total_matches"] = totalMatches

	return statistics, nil
}

// ManualMatch 管理员手动匹配
func (s *AdminService) ManualMatch(req models.AdminManualMatchRequest) (*models.AdminManualMatchResponse, error) {
	// 检查课题是否存在
	var project models.Project
	if err := s.db.First(&project, req.ProjectID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("课题不存在")
		}
		return nil, err
	}

	// 检查用户是否存在
	var user models.User
	if err := s.db.First(&user, req.UserID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, fmt.Errorf("用户不存在")
		}
		return nil, err
	}

	// 检查用户角色是否为学生或导师
	if user.Role != models.RoleStudent && user.Role != models.RoleTutor {
		return nil, fmt.Errorf("只能匹配学生或导师用户")
	}

	// 检查是否已经存在匹配
	var existingMatch models.ProjectMatch
	if err := s.db.Where("project_id = ? AND user_id = ?", req.ProjectID, req.UserID).First(&existingMatch).Error; err == nil {
		return nil, fmt.Errorf("该用户已经与该课题匹配")
	}

	// 创建新的匹配记录
	match := models.ProjectMatch{
		ProjectID:  req.ProjectID,
		UserID:     req.UserID,
		MatchedAt:  time.Now(),
		MatchScore: req.MatchScore,
	}

	if err := s.db.Create(&match).Error; err != nil {
		return nil, err
	}

	// 更新课题的申请次数
	s.db.Model(&project).Update("apply_count", gorm.Expr("apply_count + ?", 1))

	// 创建通知
	notification := models.Notification{
		UserID:      req.UserID,
		Title:       "新的课题匹配",
		Content:     fmt.Sprintf("您已被管理员匹配到课题「%s」，请及时查看并确认。", project.Title),
		Type:        "match",
		RelatedID:   &req.ProjectID,
		RelatedType: "project",
	}

	if err := s.db.Create(&notification).Error; err != nil {
		// 通知创建失败不影响匹配结果
	}

	return &models.AdminManualMatchResponse{
		MatchID:   match.ID,
		ProjectID: req.ProjectID,
		UserID:    req.UserID,
		Message:   "匹配成功",
	}, nil
}

// GetMatchCandidates 获取课题的匹配候选者
func (s *AdminService) GetMatchCandidates(projectID uint, role string) ([]models.User, error) {
	var users []models.User

	query := s.db.Model(&models.User{}).Where("role = ? AND status = ?", role, models.StatusApproved)

	// 排除已经匹配的用户
	query = query.Where("id NOT IN (SELECT user_id FROM project_matches WHERE project_id = ?)", projectID)

	// 预加载用户详细信息
	if role == string(models.RoleStudent) {
		query = query.Preload("Student")
	} else if role == string(models.RoleTutor) {
		query = query.Preload("Tutor")
	}

	if err := query.Find(&users).Error; err != nil {
		return nil, err
	}

	return users, nil
}

// GetProjectCandidates 获取用户的课题候选者
func (s *AdminService) GetProjectCandidates(userID uint) ([]models.Project, error) {
	var projects []models.Project

	// 获取开放状态的课题
	query := s.db.Model(&models.Project{}).Where("status = ?", models.ProjectStatusOpen)

	// 排除已经匹配的课题
	query = query.Where("id NOT IN (SELECT project_id FROM project_matches WHERE user_id = ?)", userID)

	// 预加载创建者信息
	query = query.Preload("Creator")

	if err := query.Find(&projects).Error; err != nil {
		return nil, err
	}

	return projects, nil
}

// RemoveMatch 移除匹配
func (s *AdminService) RemoveMatch(matchID uint) error {
	var match models.ProjectMatch
	if err := s.db.First(&match, matchID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return fmt.Errorf("匹配记录不存在")
		}
		return err
	}

	// 删除匹配记录
	if err := s.db.Delete(&match).Error; err != nil {
		return err
	}

	// 更新课题的申请次数
	s.db.Model(&models.Project{}).Where("id = ?", match.ProjectID).
		Update("apply_count", gorm.Expr("apply_count - ?", 1))

	// 创建通知
	notification := models.Notification{
		UserID:      match.UserID,
		Title:       "匹配已移除",
		Content:     "您与课题的匹配已被管理员移除。",
		Type:        "match_removed",
		RelatedID:   &match.ProjectID,
		RelatedType: "project",
	}

	if err := s.db.Create(&notification).Error; err != nil {
		// 通知创建失败不影响移除结果
	}

	return nil
}

// GetMatches 获取所有匹配记录
func (s *AdminService) GetMatches(page, size int) ([]models.ProjectMatch, int64, error) {
	var matches []models.ProjectMatch
	var total int64

	query := s.db.Model(&models.ProjectMatch{})

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 分页查询
	offset := (page - 1) * size
	if err := query.Preload("Project").
		Preload("User").
		Offset(offset).
		Limit(size).
		Order("created_at DESC").
		Find(&matches).Error; err != nil {
		return nil, 0, err
	}

	return matches, total, nil
}
